<template>
  <div>
    <el-row>
      <el-col style="margin-top: 30px">
        <el-button
          type="primary"
          plain
          style="width: 20%"
          @click="dialogFormVisible1 = true"
          >新增视频</el-button
        >
        <!-- <el-button
          type="primary"
          plain
          style="width: 20%"
          @click="bt_2()"
          :class="{ 'active-button': reply === 2 }"
          >已回复</el-button
        > -->
      </el-col>

      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
          v-if="Data != null"
        >
          <el-table-column
            prop="title"
            label="视频标题"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="photocontent"
            label="视频图示"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <div style="width: 50%; height: 100px; margin: auto">
                <img :src="scope.row.photocontent" />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="videocontent"
            label="视频链接"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <a :href="scope.row.videocontent" class="text-ellipsis">{{
                scope.row.videocontent
              }}</a>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" align="center" width="auto">
            <template #default="scope">
              <!-- <el-button
                style="color: green"
                link
                type="primary"
                size="small"
                @click="editGoods(scope.row)"
                >修改</el-button
              > -->
              <el-button
                link
                style="color: red"
                type="primary"
                size="small"
                @click="delBerbak(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <el-dialog
        title="文章修改"
        v-model="dialogFormVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form :model="add" label-position="right">
          <el-form-item label="文章标题:" label-width="100px">
            <el-input v-model="add.messagetype"></el-input>
          </el-form-item>
          <el-form-item label="文章链接" label-width="100px">
            <el-input v-model="add.content"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin-top: 10px">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="新增视频"
        v-model="dialogFormVisible1"
        width="30%"
        :before-close="handleClose1"
      >
        <el-form :model="form" label-position="right">
          <el-form-item label="视频标题:" label-width="100px">
            <el-input v-model="form.messagetype"></el-input>
          </el-form-item>
        </el-form>
        <!-- <div>
          <div v-if="imageUrl" style="margin: auto; width: 80%">
            <img :src="imageUrl" style="max-width: 100%; max-height: 300px" />
          </div>
          <label for="fileInput" class="custom-button w">上传视频封面</label>
          <input
            type="file"
            id="fileInput"
            accept="image/*"
            @change="handleFileChange"
          />
        </div> -->

        <div class="video-upload-container">
          <!-- 显示图片的区域 -->
          <div v-if="imageUrl" style="margin: auto; width: 80%">
            <img :src="imageUrl" style="max-width: 100%; max-height: 300px" />
          </div>

          <!-- 图片选择按钮 -->
          <label for="fileInput" class="custom-button w">上传视频封面</label>
          <input type="file" id="fileInput" accept="image/*" @change="handleFileChange" />
          <!-- 隐藏文件输入框 -->
          <input
            type="file"
            id="videoInput"
            @change="handleFileChange_shipin"
            accept="video/*"
            ref="videoInput"
          />

          <!-- 自定义按钮来触发文件选择 -->
          <label for="videoInput" class="custom-file-button w">选择视频</label>

          <!-- 上传按钮 -->
          <button
            @click="uploadVideo"
            :disabled="!videoFile || uploading"
            class="upload-button w"
          >
            上传视频
          </button>

          <!-- 上传状态提示 -->
          <div v-if="uploading" class="status-message uploading w">上传中...</div>
          <div v-if="uploadSuccess" class="status-message success w">上传成功！</div>
          <!-- <div v-if="uploadError" class="status-message error w">上传失败，请重试！</div> -->
        </div>
        <!-- <div slot="footer" class="dialog-footer" style="margin-top: 10px">
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="submit_add">确 定</el-button>
        </div> -->
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeMount } from "vue";
import apiService from "@/services/apiService";
import { v4 as uuidv4 } from "uuid";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Liuyan",
});

//表格数据
const Data = ref<any>([
  {
    messagetype: "测试",
    content: "https:111111",
  },
]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const reply = ref<number>(1); //当前显示

//获取表单数据
const GetList = () => {
  const params = {
    msgid: "PagingFindKnowledge",
    token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value,
      type: "科谱视频",
    },
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      let arr = res.data.body.knowledges;
      // for (let i = 0; i < arr.length; i++) {
      //   arr[i].createtime =
      //     arr[i].createtime.slice(0, 10) + " " + arr[i].createtime.slice(11);
      // }
      Data.value = arr;
      Total.value = res.data.body.totalCount;
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

// 监听页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
};

//删除
const delBerbak = (row: any) => {
  ElMessageBox.confirm("确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const params = {
        msgid: "DeleteKnowledgeArticle",
        token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
        seq: uuidv4(),
        body: {
          knowledgeId: row.id,
        },
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });

          GetList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//新增文章
const dialogFormVisible1 = ref(false);
const add = ref<any>({});

// 组件的响应式数据
const imageUrl = ref<string | null>(null); // 用于显示图片的 URL
const base64Image = ref<string | null>(null); // 用于存储 Base64 图片数据
// 选择图片后触发的函数
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = () => {
      // 显示图片
      imageUrl.value = reader.result as string;
      // 获取 Base64 字符串（去掉前缀部分）
      base64Image.value = (reader.result as string).split(",")[1];
    };

    reader.readAsDataURL(file);
  }
};
const submit_add = () => {};
//编辑回复
const dialogFormVisible = ref(false);
const form = reactive({
  messagetype: "",
  content: "",
  id: "",
});
const back = ref("");
const back_List = ref([]);
const editGoods = (row: any) => {
  console.log("回复");
  form.messagetype = row.messagetype;
  form.content = row.content;
  form.id = row.id;
  back_List.value = row.writemsgs;
  dialogFormVisible.value = true;
};

//回复按钮
const submit = () => {
  ElMessageBox.confirm("确定添加回复吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const utcDate = ref<any>();
      var date = new Date();
      utcDate.value = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
      console.log(utcDate.value);

      const params = {
        msgid: "InsertWriteMsg",
        token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
        seq: uuidv4(),
        body: {
          leavemsgid: form.id,
          content: back.value,
          messagetypeid: 2,
          // fileid:'',
          createtime: utcDate.value,
        },
      };
      apiService.post("", params).then((res: any) => {
        console.log(res);
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "回复成功",
          });
          GetList();

          back.value = "";
          dialogFormVisible.value = false;
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消回复",
      });
      dialogFormVisible.value = false;
    });
};
//关闭弹窗
const handleClose = (done: () => void) => {
  // ElMessageBox.confirm("确认关闭?")
  //   .then(() => {
  back.value = "";
  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};
const handleClose1 = (done: () => void) => {
  // ElMessageBox.confirm("确认关闭?")
  //   .then(() => {
  console.log("1");
  form.messagetype = "";
  imageUrl.value = "";
  uploading.value = false; // 上传状态
  uploadSuccess.value = false; // 上传状态

  done();
  // })
  // .catch(() => {
  //   // catch error
  // });
};

//上传视频
const videoFile = ref<any>(""); // 当前选择的文件
const uploading = ref(false); // 上传状态
const uploadSuccess = ref(false); // 上传成功标志
const videoType = ref<any>(""); //文件类型
// 处理文件选择
const handleFileChange_shipin = (event: Event) => {
  const input = event.target as HTMLInputElement;
  console.log("上传文件", input.files[0]);

  if (input.files && input.files[0]) {
    videoFile.value = input.files[0];
    uploadSuccess.value = false;
    videoType.value = input.files[0].name;
  }
};

// 上传视频函数
const uploadVideo = async () => {
  // if (!videoFile.value) return;
  if (videoFile.value != "" && imageUrl.value != "" && form.messagetype != "") {
    uploading.value = true;

    const params = new FormData();
    params.append("video", videoFile.value);
    // params.append("image", imageUrl.value);
    // params.append("title", form.messagetype);
    console.log(params);
    // 获取 form.messagetype 的值
    let messageType = videoType.value; // 例如: "中文类型"
    // 将 messageType 编码为 UTF-8 格式
    let encodedMessageType = encodeURIComponent(messageType);
    // 将 UTF-8 编码的字符串转为 Base64
    let base64MessageType = btoa(unescape(encodedMessageType));

    // try {
    apiService
      .post("", params, {
        headers: {
          // "Content-Type": "multipart/form-data", // 设置请求头为 multipart/form-data
          "Content-Type": "application/octet-stream",
          msgid: "UploadFile",
          token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
          seq: uuidv4(),
          // fileName: base64MessageType,
          type: base64MessageType,
        },
      })
      .then((res: any) => {
        console.log(res);
        if (res.data.code === 200) {
          const params = {
            msgid: "AddKnowledgeVideo",
            token: "BC65FD34-931E-6E6D-7979-EFD67A547B56",
            seq: uuidv4(),
            body: {
              title: form.messagetype,
              videoId: res.data.body.id,
              coverBase64: base64Image.value,
              type:'png'
            },
          };

          apiService
            .post("", params)
            .then((res: any) => {
              // 使用 any 类型断言
              console.log(res.data);
              ElMessage({
                type: "success",
                message: "添加成功",
              });
              uploading.value = false;
              uploadSuccess.value = true;
              dialogFormVisible1.value = false;
              GetList();
            })
            .catch((error) => {
              console.error("Error fetching data:", error);
            });
        }
      });
  } else {
    ElMessage({
      type: "error",
      message: "请填写完整信息",
    });
  }
};

onMounted(() => {
  GetList();
});
</script>

<style lang="scss" scoped>
.w {
  width: 80%;
}
.active-button {
  background-color: #409eff; /* 设置按钮激活时的背景颜色 */
  color: white; /* 设置按钮激活时的文字颜色 */
}
/* 隐藏原生文件选择框 */
input[type="file"] {
  display: none;
}

/* 自定义按钮样式 */
.custom-button {
  display: inline-block;
  background-color: #409eff;
  color: white;
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
  text-align: center;
}

/* 你可以根据需要调整输入框的布局 */
.file-upload-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.video-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

button:disabled {
  background-color: #ccc;
}

.error {
  color: red;
}
/* 视频上传容器 */
.video-upload-container {
  // max-width: 400px;
  // margin: 0 auto;
  // padding: 20px;
  // text-align: center;
  // border: 1px solid #ddd;
  // border-radius: 8px;
  // background-color: #f9f9f9;
}

/* 隐藏默认的文件输入框 */
input[type="file"] {
  display: none;
}

/* 自定义文件选择按钮 */
.custom-file-button {
  display: inline-block;
  background-color: #409eff;
  color: white;
  padding: 10px 20px;
  text-align: center;
  cursor: pointer;
  border-radius: 5px;
  font-size: 16px;
  margin-bottom: 15px;
  transition: background-color 0.3s;
  margin-top: 20px;
}

.custom-file-button:hover {
  background-color: #409eff;
}

.custom-file-button:active {
  background-color: #409eff;
}

/* 上传按钮样式 */
.upload-button {
  background-color: #2196f3;
  color: white;
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-button:disabled {
  background-color: #b0bec5;
  cursor: not-allowed;
}

.upload-button:hover:not(:disabled) {
  background-color: #1976d2;
}

.upload-button:active:not(:disabled) {
  background-color: #1565c0;
}

/* 状态信息样式 */
.status-message {
  margin-top: 10px;
  padding: 10px;
  border-radius: 5px;
  font-size: 14px;
  font-weight: bold;
}

.uploading {
  background-color: #ff9800;
  color: white;
  text-align: center;
}

.success {
  background-color: #4caf50;
  color: white;
}

.error {
  background-color: #f44336;
  color: white;
}
.text-ellipsis {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>
